package com.ai.service.made.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ai.common.CommonResponse;
import com.ai.common.constant.Constants;
import com.ai.common.constant.FunctionTypeConstants;
import com.ai.entity.BasePage;
import com.ai.entity.made.CoalCraneInspection;
import com.ai.entity.made.CoalMaintenanceAlarmRecord;
import com.ai.entity.made.CoalMaintenanceAlarmRecordInfo;
import com.ai.entity.made.RegionBase;
import com.ai.entity.made.camera.CameraPO;
import com.ai.mapper.made.CoalMaintenanceAlarmRecordMapper;
import com.ai.model.dto.CoalMaintenanceAlarmRecordDto;
import com.ai.model.page.CoalMaintenancePage;
import com.ai.model.vo.CoalMaintenanceVo;
import com.ai.service.made.*;
import com.ai.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiaok
 * @since 2024-10-30
 */
@Service
@Slf4j
public class CoalMaintenanceAlarmRecordServiceImpl extends ServiceImpl<CoalMaintenanceAlarmRecordMapper, CoalMaintenanceAlarmRecord> implements ICoalMaintenanceAlarmRecordService {

    @Resource
    private CameraService cameraService;

    @Resource
    private  ICoalMaintenanceAlarmRecordInfoService iCoalMaintenanceAlarmRecordInfoService;

    @Resource
    IRegionManageService iRegionManageService;

    @Resource
    IRegionBaseService iRegionBaseService;


    @Resource
    private ICoalCraneInspectionService iCoalCraneInspectionService;

    @Resource
    private CameraFunctionsService cameraFunctionsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse addAlarm(CoalMaintenanceAlarmRecordDto maintenanceAlarmRecordDto) {

        String maintenanceSid = maintenanceAlarmRecordDto.getMaintenanceSid();
        if (StringUtils.isBlank(maintenanceSid)){
            throw new RuntimeException("检修sid不能为空");
        }

        //首先查询当前次数的检测是否存在
        CoalMaintenanceAlarmRecord maintenanceAlarmRecord = this.getOne(
                new QueryWrapper<CoalMaintenanceAlarmRecord>().eq("maintenance_sid", maintenanceSid));

        //处理检修主记录（维护状态）
        if (ObjectUtil.isEmpty(maintenanceAlarmRecord)){
            //说明当前为该班次第一次检修
            maintenanceAlarmRecord = getFirstCoalMaintenanceAlarmRecord(maintenanceAlarmRecordDto);
            this.save(maintenanceAlarmRecord);
        }else {
            //处理非第一次检修情况
            CommonResponse<Object> optNotFirstCoalRes =
                    optNotFirstCoalMaintenanceAlarmRecord(maintenanceAlarmRecordDto, maintenanceAlarmRecord);
            if (optNotFirstCoalRes != null) {
                return optNotFirstCoalRes;
            }
        }

        //处理检修详情
       if (!maintenanceAlarmRecordDto.getIsFinalReq()){
           //开始新增检修详细信息
           handleMaintenanceDetailAlarmRecord(maintenanceAlarmRecordDto, maintenanceAlarmRecord);
       }


        return CommonResponse.ok("单轨吊检修告警接收成功");
    }

    /**
     * 处理检修详情信息
     * @param maintenanceAlarmRecordDto 检修告警参数
     * @param maintenanceAlarmRecord 检修主记录db实例
     */
    private void handleMaintenanceDetailAlarmRecord(CoalMaintenanceAlarmRecordDto maintenanceAlarmRecordDto, CoalMaintenanceAlarmRecord maintenanceAlarmRecord) {
        CoalMaintenanceAlarmRecordInfo coalMaintenanceAlarmRecordInfo = new CoalMaintenanceAlarmRecordInfo();
        BeanUtils.copyProperties(maintenanceAlarmRecordDto,coalMaintenanceAlarmRecordInfo);
        coalMaintenanceAlarmRecordInfo.setCoalMaintenanceId(maintenanceAlarmRecord.getId());
        coalMaintenanceAlarmRecordInfo.setBeginMaintenanceTime(DateUtil.parseLocalDateTime(maintenanceAlarmRecordDto.getBeginMaintenanceTime()));
        coalMaintenanceAlarmRecordInfo.setEndMaintenanceTime(DateUtil.parseLocalDateTime(maintenanceAlarmRecordDto.getEndMaintenanceTime()));
        coalMaintenanceAlarmRecordInfo.setCreateTime(LocalDateTime.now());
        coalMaintenanceAlarmRecordInfo.setUpdateTime(LocalDateTime.now());
        coalMaintenanceAlarmRecordInfo.setCreateUser(Constants.ALGORITHM_SYSTEM);
        coalMaintenanceAlarmRecordInfo.setUpdateUser(Constants.ALGORITHM_SYSTEM);
        iCoalMaintenanceAlarmRecordInfoService.save(coalMaintenanceAlarmRecordInfo);
    }

    /**
     * 非第一次检修，更新总检修状态
     * @param maintenanceAlarmRecordDto 检修告警入参
     * @param maintenanceAlarmRecord  db检修实例
     * @return
     */
    private CommonResponse<Object> optNotFirstCoalMaintenanceAlarmRecord(CoalMaintenanceAlarmRecordDto maintenanceAlarmRecordDto, CoalMaintenanceAlarmRecord maintenanceAlarmRecord) {
        maintenanceAlarmRecord.setMaintenanceState(maintenanceAlarmRecordDto.getMaintenanceState());

        maintenanceAlarmRecord.setUpdateUser(Constants.ALGORITHM_SYSTEM);
        if (maintenanceAlarmRecordDto.getIsFinalReq()){
            //如果是最后一次请求
            List<CoalCraneInspection> craneInspectionList = iCoalCraneInspectionService.list();
            //检修结束时间
            String endTime = craneInspectionList.get(0).getEndTime();
            //获取对应子表最大的日期
            String finalDate = iCoalMaintenanceAlarmRecordInfoService.getFinalMaintenanceDate(maintenanceAlarmRecord.getId());
            String state = iCoalCraneInspectionService.getMaintenanceState(maintenanceAlarmRecord.getAccumulatedDuration(),maintenanceAlarmRecordDto.getCameraId(), FunctionTypeConstants.MONORAIL_STATION_DETECTION);
            maintenanceAlarmRecord.setMaintenanceState(state);
            maintenanceAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(finalDate+" "+endTime));
            this.updateById(maintenanceAlarmRecord);
            return CommonResponse.ok("单轨吊检修告警接收成功");
        }else {
            maintenanceAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(maintenanceAlarmRecordDto.getEndMaintenanceTime()));
        }

        //追加累计时长
        maintenanceAlarmRecord.setAccumulatedDuration(maintenanceAlarmRecordDto.getMaintenanceDuration()+ maintenanceAlarmRecord.getAccumulatedDuration());
        this.updateById(maintenanceAlarmRecord);
        return null;
    }



    /**
     * 创建单轨吊第一次告警
     * @param maintenanceAlarmRecordDto 单轨吊检修实例
     * @return 第一次告警实例
     */
    private CoalMaintenanceAlarmRecord getFirstCoalMaintenanceAlarmRecord(CoalMaintenanceAlarmRecordDto maintenanceAlarmRecordDto) {
        CoalMaintenanceAlarmRecord maintenanceAlarmRecord;
        maintenanceAlarmRecord = new CoalMaintenanceAlarmRecord();
        BeanUtils.copyProperties(maintenanceAlarmRecordDto,maintenanceAlarmRecord);
        CameraPO cameraPO = cameraService.getById(maintenanceAlarmRecordDto.getCameraId());
        if (ObjectUtil.isEmpty(cameraPO)){
            throw new RuntimeException("cameraId对应的摄像头不存在，请检查后重新发送");
        }
        maintenanceAlarmRecord.setCameraCode(cameraPO.getCode());
        //追加检修累计时间
        maintenanceAlarmRecord.setAccumulatedDuration(maintenanceAlarmRecordDto.getMaintenanceDuration());

        maintenanceAlarmRecord.setCreateUser(Constants.ALGORITHM_SYSTEM);
        maintenanceAlarmRecord.setUpdateUser(Constants.ALGORITHM_SYSTEM);
        maintenanceAlarmRecord.setCreateTime(LocalDateTime.now());
        //用于存储最后检修的结束时间
        if (maintenanceAlarmRecordDto.getIsFinalReq()){
            List<CoalCraneInspection> craneInspectionList = iCoalCraneInspectionService.list();
            //检修结束时间
            String endTime = craneInspectionList.get(0).getEndTime();
            LocalDate endMaintenanceDate = LocalDate.now().minusDays(1);
            //最后一次检修的记录时间为对应配置的
            String state = iCoalCraneInspectionService.getMaintenanceState(maintenanceAlarmRecord.getAccumulatedDuration(),maintenanceAlarmRecordDto.getCameraId(), FunctionTypeConstants.MONORAIL_STATION_DETECTION);
            maintenanceAlarmRecord.setMaintenanceState(state);
            maintenanceAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(endMaintenanceDate+ " " +endTime));
        }else {
            maintenanceAlarmRecord.setUpdateTime(DateUtil.parseLocalDateTime(maintenanceAlarmRecordDto.getEndMaintenanceTime()));
        }
        return maintenanceAlarmRecord;
    }



    @Override
    public CommonResponse coalMaintenanceList(CoalMaintenancePage coalMaintenancePage) {

        BasePage<CoalMaintenanceVo> coalMaintenanceVoBasePage = new BasePage<CoalMaintenanceVo>();

        List<String> cameraIdList = new ArrayList<>();
        if (StrUtil.isNotEmpty(coalMaintenancePage.getRegionBaseId())){
            //获取其组织下的所有摄像头id
            cameraIdList = iRegionManageService.getBelowCameraIdList(coalMaintenancePage.getRegionBaseId());
        }else {
            //获取当前登录用户下的所有设摄像头id
            cameraIdList = iRegionManageService.getBelowCameraIdList(SecurityUtils.getLoginRegionBaseId());
        }

        if (CollectionUtils.isEmpty(cameraIdList)){
            //当前区域没有管理任何摄像头
            return CommonResponse.ok(coalMaintenanceVoBasePage);
        }
        coalMaintenancePage.setCameraIdList(cameraIdList);
//        //获取当前区域管理的摄像头
//        HashMap<String,String> cameraRegionMap = SecurityUtils.getRegionManageCamerasCode(iRegionBaseService, iRegionManageService);
//        if (CollectionUtils.isEmpty(cameraRegionMap)){
//            //当前区域没有管理任何摄像头
//            return CommonResponse.ok(coalMaintenancePage);
//        }
        //获取所有摄像头code
//        if (org.springframework.util.StringUtils.isEmpty(coalMaintenancePage.getRegionBaseId())) {
//            ArrayList<String> cameraCodes = new ArrayList<>(cameraRegionMap.keySet());
//            coalMaintenancePage.setCameraCodes(cameraCodes);
//        }else{
//            CommonResponse bindList = iRegionManageService.getBindList(coalMaintenancePage.getRegionBaseId());
//            ArrayList<String> bindListData = (ArrayList<String>) bindList.getData();
//            coalMaintenancePage.setCameraCodes(bindListData);
//        }
//        log.info("===========================  cameraCodes  ===========================,{}",coalMaintenancePage.getCameraCodes());

        QueryWrapper<CoalMaintenanceAlarmRecord> recordQueryWrapper = new QueryWrapper<>();
        QueryWrapper<CoalMaintenanceAlarmRecord> alarmRecordQueryWrapper = coalMaintenancePage.getQuery(recordQueryWrapper);
        CoalMaintenancePage maintenancePage = page(coalMaintenancePage, alarmRecordQueryWrapper);
        List<CoalMaintenanceAlarmRecord> recordList = maintenancePage.getRecords();

        if (CollectionUtils.isEmpty(recordList)){
            return CommonResponse.ok(maintenancePage);
        }

        LinkedList<CoalMaintenanceVo> coalMaintenanceVos = new LinkedList<>();
        for (CoalMaintenanceAlarmRecord coalMaintenanceAlarmRecord : recordList) {

            CoalMaintenanceVo coalMaintenanceVo = new CoalMaintenanceVo();
            BeanUtils.copyProperties(coalMaintenanceAlarmRecord,coalMaintenanceVo);

            CameraPO cameraPO = cameraService.getById(coalMaintenanceAlarmRecord.getCameraId());
            RegionBase regionBase = iRegionBaseService.getById(cameraPO.getRegionId());
            coalMaintenanceVo.setRegionName(regionBase.getRegionName());
            coalMaintenanceVo.setCameraNickname(cameraPO == null ? "" : cameraPO.getNickname());
            String state = iCoalCraneInspectionService.getMaintenanceState(coalMaintenanceAlarmRecord.getAccumulatedDuration()
                    ,coalMaintenanceAlarmRecord.getCameraId()
                    , FunctionTypeConstants.MONORAIL_STATION_DETECTION);
            coalMaintenanceVo.setMaintenanceState(state);

            coalMaintenanceVos.add(coalMaintenanceVo);
        }

        BeanUtils.copyProperties(maintenancePage,coalMaintenanceVoBasePage);
        coalMaintenanceVoBasePage.setRecords(coalMaintenanceVos);

        return CommonResponse.ok(coalMaintenanceVoBasePage);
    }

    @Override
    public CommonResponse test() {
        CoalMaintenanceAlarmRecordInfo endMaintenanceInfo = iCoalMaintenanceAlarmRecordInfoService.getOne(new QueryWrapper<CoalMaintenanceAlarmRecordInfo>()
                .select("MAX(end_maintenance_time)")
                .eq("coal_maintenance_id", "e71f666b5400ebc36d581a848874fa3c"));
        LocalDateTime endMaintenanceTime = endMaintenanceInfo.getEndMaintenanceTime();
        return CommonResponse.ok(endMaintenanceTime);
    }
}
